<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>${s_UserPharmacy.pharmacy.name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>


<script src="<c:url value="/resources/js/ui/minified/jquery.ui.core.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.widget.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.position.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.mouse.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.button.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.draggable.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.resizable.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.datepicker.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.ui.dialog.min.js" />"></script>
<script src="<c:url value="/resources/js/ui/minified/jquery.effects.core.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.form.js" />"></script>
<script src="<c:url value="/resources/js/jquery-1.9.1.js" />"></script>
<script src="<c:url value="/resources/js/ui/jquery-ui.js" />"></script>
<script src="<c:url value="/resources/js/validate/jquery.validate.min.js" />"></script>



<fmt:message key="form.selected" var="selected"/>	

<script type="text/javascript">
$(function() {
    
	  $.datepicker.regional['es'] = 
	  {
	  closeText: 'Cerrar', 
	  prevText: 'Previo', 
	  nextText: 'Próximo',
	  
	  monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
	  'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
	  monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
	  'Jul','Ago','Sep','Oct','Nov','Dic'],
	  monthStatus: 'Ver otro mes', yearStatus: 'Ver otro año',
	  dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
	  dayNamesShort: ['Dom','Lun','Mar','Mie','Jue','Vie','Sáb'],
	  dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sa'],
	  dateFormat: 'dd/mm/yy', firstDay: 0, 
	  initStatus: 'Selecciona la fecha', isRTL: false};
	  $.datepicker.setDefaults($.datepicker.regional['es']);
});
	
	var listPharmacyTemp = [];
	<c:forEach var="item" items="${listPharmacy}">
		var listUserPharmacyTemp = [];
		<c:forEach var="userpharmacyTemp" items="${item.userpharmacyCollection}">
			var listTransactionTemp = [];
			<c:forEach var="transactionTemp" items="${userpharmacyTemp.transactionCollection}">
				var transaction = {
						periodIds:"<c:out value="${transactionTemp.transactionPK.periodIds}"/>",
						transactionId:"<c:out value="${transactionTemp.transactionPK.transactionId}"/>",
						units:"<c:out value="${transactionTemp.units}"/>",
						amount:"<c:out value="${transactionTemp.amount}"/>",
						dateTransaction:"<c:out value="${transactionTemp.dateTransaction}"/>",
						userId:"<c:out value="${transactionTemp.userpharmacy.userpharmacyPK.userId}"/>",
						pharmacyId:"<c:out value="${transactionTemp.userpharmacy.userpharmacyPK.pharmacyId}"/>"
				};
				listTransactionTemp.push(transaction);
			</c:forEach>
			var userTemp = {userId:"<c:out value="${userpharmacyTemp.user.userId}"/>",name:"<c:out value="${userpharmacyTemp.user.name}"/>"};	
			var userpharmacy = {pharmacyId:"<c:out value="${userpharmacyTemp.userpharmacyPK.pharmacyId}"/>",
								userId:"<c:out value="${userpharmacyTemp.userpharmacyPK.userId}"/>",
								active:"<c:out value="${userpharmacyTemp.active}"/>",
								transactionCollection:listTransactionTemp,
								user:userTemp};
			listUserPharmacyTemp.push(userpharmacy);
		</c:forEach>
				
		var pharmacy = {pharmacyId:"<c:out value="${item.pharmacyId}"/>",
						userpharmacyCollection:listUserPharmacyTemp,
						name:"<c:out value="${item.name}"/>"};
		listPharmacyTemp.push(pharmacy);
	</c:forEach>
	
	
	
	var listUserPharmacy = [];
	var isEmptyTable = true;
	
	$(document).ready(function(){		
		$( "#tabs" ).tabs(); // inicializa los tabs
		$('.numbersOnly').keyup(function () {
			if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
				this.value = this.value.replace(/[^0-9\.]/g, '');
			}
		});
		$('.lettersOnly').keyup(function () {
			if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
				this.value = this.value.replace(/[^A-Za-z\s]/g, '');
			}
		});
		
		
		$("#formTransaction").validate({
	        submitHandler: function(form) {
	        	pressButton();
	        }
	    });
		
		$("input[name='typeDate_0']").change(function(){
	        var tipoFecha = parseInt($("input[name='typeDate_0']:checked").val(),10);
	        if(tipoFecha == 2){
	            $("#divByDate").css("display", "none");
	            $("#divByRangeDate").css("display", "block");
	        }else{
	        	$("#divByDate").css("display", "block");
	            $("#divByRangeDate").css("display", "none");
	        }
	    });   
		$( "#fecha_0" ).datepicker({
			minDate: "-2Y",
			changeMonth: true,
			numberOfMonths: 3,
			maxDate: 0,
			showButtonPanel: true
		});    
		$( "#dateFrom_0" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 3,
			onClose: function( selectedDate ) {
				$( "#dateTo_0" ).datepicker( "option", "minDate", selectedDate );
			}
		});
		$( "#dateTo_0" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 3,
			onClose: function( selectedDate ) {
				$( "#dateFrom_0" ).datepicker( "option", "maxDate", selectedDate );
			}
		});
				
		$("#pharmacyId").change(function(){ // action change to contries
			listUserPharmacy = [];
			var pharmacyId = $(this).val();
			var element = $("#userId");
			element.empty().append("<option value=''><c:out value="${selected}"/></option>");
			if(pharmacyId != ""){
				for (var i = 0; i < listPharmacyTemp.length; i++) {
					var obji = listPharmacyTemp[i];
					if(pharmacyId == obji.pharmacyId){
						for (var j = 0; j < obji.userpharmacyCollection.length; j++) {
							objj = obji.userpharmacyCollection[j];
							var activeUser = false;
							for (var k = 0; k < objj.transactionCollection.length; k++) {
								var transaction = objj.transactionCollection[k];
								if(transaction.userId == objj.userId && transaction.pharmacyId == objj.pharmacyId){
									activeUser = true;									
								}
							}
							if(activeUser){
								element.append("<option value='"+objj.user.userId+"'>"+objj.user.name+"</option>");
								listUserPharmacy.push(objj);
							}
						}
					}else{
						for (var j = 0; j < obji.userpharmacyCollection.length; j++) {
							objj = obji.userpharmacyCollection[j];
							var activeUser = false;
							for (var k = 0; k < objj.transactionCollection.length; k++) {
								var transaction = objj.transactionCollection[k];
								if(transaction.userId == objj.userId && transaction.pharmacyId == objj.pharmacyId){
									activeUser = true;									
								}
							}
							if(activeUser){
								listUserPharmacy.push(objj);
							}
						}
					}
				}
				var s='';
				if(pharmacyId == "-100")
					s="selected='selected'";
				element.append('<option value="-100" '+s+'><fmt:message key="show.form.selectedAll"/></option>');
			}			
		});
		
		
	});	
		
	function loadListByDateStartByDateEnd(dateStart,dateEnd,userId,html){	
		if(( $('input:radio[name=typeDate_0]:checked').val() == 1 && $("#fecha_0").val() != '') || ($('input:radio[name=typeDate_0]:checked').val() == 2 && $("#dateFrom_0").val() != '' && $("#dateTo_0").val() != '')){
			$.ajax({ 
	    		type: "GET",
	    		url	: 'economicReportsByDateStartByDateEnd',
	       	   	dataType: "json",		
	            data: {dateStart:dateStart,dateEnd:dateEnd,userId:userId,radioSelected:$('input:radio[name=typeDate_0]:checked').val()},
	       	    success:function(data){	   
	       	    	
	       	    	//alert(listUserPharmacy.length+'  ; '+listPharmacyTemp.length);
	       	    	isEmptyTable = true;
	       	    	
	       	    	for (var i = 0; i < listPharmacyTemp.length; i++){
	       	    		var objPharmacy = listPharmacyTemp[i];
	       	    		if($("#pharmacyId").val() != -100 ){
		       	    		for (var j = 0; j < listUserPharmacy.length; j++) {
								var obj = listUserPharmacy[j];
								if($("#pharmacyId").val() == objPharmacy.pharmacyId && obj.pharmacyId == objPharmacy.pharmacyId){
				       	    		if($("#userId").val() != -100){
										if($("#userId").val() == obj.user.userId){
											html += loadTable(data,$("#userId").val(),obj.pharmacyId);
										}
									}else
										html += loadTable(data,obj.user.userId,obj.pharmacyId);
								}
							}
	       	    		}else{
	       	    			for (var j = 0; j < listUserPharmacy.length; j++) {
								var obj = listUserPharmacy[j];
								if(obj.pharmacyId == objPharmacy.pharmacyId)
			       	    			html += loadTable(data,obj.user.userId,obj.pharmacyId);
							}
	       	    		}
	       	    	}	 
	       	    	if(isEmptyTable){
       	    			html+='	<div>'+
	       	 			'			<table class="tabla_decorado" id="mainContainerTable" style="width: 100%">'+
	       	 			'				<thead>'+
	       	 			'					<tr>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.placeOfTransaction"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.dateTransaction"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.timeTransaction"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.operation"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.client"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.numBill"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.entry"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.egress"/></th>'+
	       	 			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.total"/></th>'+
	       	 			'					</tr>'+
	       	 			'				</thead>'+				
	       	 			'				<tbody>'+
		       	 		'				<tr class="tr_decorado">'+
	               		'					<td class="td_decorado" colspan="9" style="text-align:center"><span style="color:red"><fmt:message key="show.noExistTransaction"/></span></td>'+
	               		'				</tr>'+
       	 				'				</tbody>'+				
       					'			</table>'+
       					'		</div>';
       	    		}
	       	    	$("#mainShowTable").html(html);
	       		}, 
	       		error: 	function(){alert('Error in request..from economicReportsByDateStartByDateEnd ');} }); 
		}else			
			$("#mainShowTable").html('');
	}

	function loadTable(dataTemp,userId,pharmacyId){		
		var data = [];		
		for(var i=0; i<dataTemp.length; i++){
			var obj3 = dataTemp[i];
			if(obj3 != null && userId == obj3.userpharmacy.user.userId && pharmacyId == obj3.userpharmacy.pharmacy.pharmacyId)
				data.push(obj3);
		}	
		var html='';
		if(data.length > 0){
			html+='	<div>';
			if($("#pharmacyId").val() == -100)
				html+='	<h2 class="decorado"><fmt:message key="show.userOfThePharmacy"/> : '+data[0].userpharmacy.pharmacy.name+'</h2></br>';
			html+='		<table style="width: 100%">'+
    		'				<tr>'+
    		'					<td><label><b><fmt:message key="form.name"/>: </b>'+data[0].userpharmacy.user.name+'</label></td>'+
    		'				</tr>'+
    		'				<tr>'+
    		'					<td><label><b><fmt:message key="form.lastNames"/>: </b>'+data[0].userpharmacy.user.lastName+' '+data[0].userpharmacy.user.lastName2+'</label></td>'+
    		'				</tr>'+
    		'			</table>'+			
			'			<table class="tabla_decorado" id="mainContainerTable" style="width: 100%">'+
			'				<thead>'+
			'					<tr>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.placeOfTransaction"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.dateTransaction"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.timeTransaction"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.operation"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.client"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.numBill"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.entry"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.egress"/></th>'+
			'						<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.total"/></th>'+
			'					</tr>'+
			'				</thead>'+				
			'				<tbody>';
			for(var i=0; i<data.length; i++){
				var obj = data[i];
				if(obj != null){
					var d = new Date(obj.dateTransaction);
					var dateTemp = addZeroIfMinorToOther(d.getDate(),10) + '/' + addZeroIfMinorToOther((d.getMonth()+1),10) + '/' + d.getFullYear();    					
					var dateHour = addZeroIfMinorToOther(d.getHours(),10) + ':' + addZeroIfMinorToOther(d.getMinutes(),10)+ ':' + addZeroIfMinorToOther(d.getSeconds(),10);
					html+='		<tr rowIndex="'+i+'">'+
						'			<td class="th_decorado" style="text-align: center">'+obj.userpharmacy.pharmacy.locality.region.name+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+dateTemp+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+dateHour+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+obj.operationId.name+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+obj.clientId.name+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+obj.bill.billNum+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+((obj.amount > 0)?obj.amount:'')+'</td>'+
						'			<td class="th_decorado" style="text-align: center">'+((obj.amount < 0)?obj.amount:'')+'</td>'+
						'			<td class="th_decorado" style="text-align: center"> totales </td>'+
						'		</tr>';
				}
			}
			html+='			</tbody>'+				
			'			</table>'+
			'		</div></br></br></br>';
			isEmptyTable = false;
		}
		return html;
	}
		
	function pressButton(){
		var text = ($('input:radio[name=typeDate_0]:checked').val() == 1)?($("#fecha_0").val()):('<fmt:message key="form.from"/>:'+$("#dateFrom_0").val()+' <fmt:message key="form.to"/> '+$("#dateTo_0").val());
		html =	'	<h2 class="decorado"><fmt:message key="title.transactions"/> '+text+'</h2></br>';
		if($('input:radio[name=typeDate_0]:checked').val() == 1){
			var date 	= $("#fecha_0").val();
			loadListByDateStartByDateEnd(date,date,$("#userId").val(),html);
		}else{
			var dateStart 	= $("#dateFrom_0").val();
			var dateEnd 	= $("#dateTo_0").val();
			loadListByDateStartByDateEnd(dateStart,dateEnd,$("#userId").val(),html);
		}
	}
	
	function addZeroIfMinorToOther(val,otherNumber){
		var temp = (val < otherNumber)?('0'+val):(val);
		return temp;
	}
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                	<li><a href="<spring:url value="/mainFront?" htmlEscape="true" />">Home</a></li>	
                    <li><span style="color:#666"><fmt:message key="title.reports"/></span></li>
                    <li class="current-page"><span class="end"><span class="middle"><fmt:message key="title.economicReports"/></span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%-- <%@include file="../../bodyIzq.jsp" %>	 --%>
                </div>
                
                <div class="der" style="border: 0px solid">
					<div id="tabs">
						<ul>
							<li><a href="#tabs-1"><fmt:message key="title.economicReports"/></a></li>
						</ul> 
						<form id="formTransaction" >
							<div id="tabs-1">
								<div style="clear: both">
									<label class="form_align43"><fmt:message key="form.typeDate"/> :</label>			
									<input type="radio" name="typeDate_0" id="radio_1" value="1" class="form_input_align_NoFloat" checked="checked" /><label for="radio_1">&nbsp;<fmt:message key="form.byDate"/> </label>&nbsp;&nbsp;
									<input type="radio" name="typeDate_0" id="radio_2" value="2"/><label for="radio_2">&nbsp;<fmt:message key="form.byRangeDate"/> </label>
								</div>    
								<div id="divByDate" style="clear: both">
									<label class="form_align43" for="fecha_0"><fmt:message key="form.date"/> :</label>
									<input type="text" name="fecha_0" id="fecha_0" class="form_input_align required" size="10" title="<fmt:message key="show.form.date"/>"/>
									<label class="error">*</label>
								</div>
								<div id="divByRangeDate" style="clear: both; display: none">
									<label class="form_align43"><fmt:message key="form.date"/> :</label>
									<label for="dateFrom_0">&nbsp;<fmt:message key="form.from"/>&nbsp;</label><input type="text" name="dateFrom_0" id="dateFrom_0" class="form_input_align_NoFloat required" size="10" title="<fmt:message key="show.form.dateFrom"/>"/>
									<label for="dateTo_0"><fmt:message key="form.to"/></label>
									<input type="text" name="dateTo_0" id="dateTo_0" class="form_input_align_NoFloat required" size="10" title="<fmt:message key="show.form.dateTo"/>"/>
									<label class="error">*</label>
								</div>
								<div style="clear:both;">
									<label for="pharmacyId" class="form_align43"><fmt:message key="form.pharmacy"/> :</label>			
									<select name="pharmacyId" id="pharmacyId" class="form_input_align required" title="<fmt:message key="show.form.selected.pharmacy"/>">
										<option value=""><fmt:message key="show.form.selected"/></option>
										<c:forEach var="item" items="${listPharmacy}">
											<option value="${item.pharmacyId}" ${selec}>${item.name}</option>
										</c:forEach> 
										<option value="-100"><fmt:message key="show.form.selectedAll"/></option>  
									</select>									
									<label class="error">*</label>
								</div>
								<div style="clear:both;">
									<label for="userId" class="form_align43"><fmt:message key="form.user"/> :</label>
									<select name="userId" id="userId" class="form_input_align required" title="<fmt:message key="show.form.selected.user"/>">
										<option value=""><fmt:message key="show.form.selected"/></option> 
									</select>
									<label class="error">*</label>
								</div>
							</div>							
							<div style="clear: both" class="form_center">
								<input type="submit" value="<fmt:message key="button.seeTransaction"/>" class="boton" title="<fmt:message key="onclick.for"/> <fmt:message key="button.seeTransaction"/>."/>
								<input type="reset" class="boton" value="<fmt:message key="button.clean"/>" />
							</div>														
						</form>
					</div>   
					<div id="mainShowTable"></div>                        
                </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
